package com.bear.richtext.utils

import android.content.Context
import android.graphics.Bitmap
import android.widget.ImageView
import com.bear.richtext.Constant
import com.bear.richtext.view.GifView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.transition.Transition

/**
 * 图片加载接口默认实现
 */
class DefaultLoadImg : ILoadImg {

    val TAG = "DefaultLoadImg"

    @OptIn(ExperimentalStdlibApi::class)
    override fun loadImg(context: Context, url: String, view: ImageView) {
        try {
            if (view is GifView) {
                Glide.with(view).load(url).into(view)
            } else {
                val target = object : com.bumptech.glide.request.target.SimpleTarget<Bitmap>() {
                    override fun onResourceReady(
                        resource: Bitmap,
                        transition: Transition<in Bitmap>?
                    ) {
                        Tools.ilog(TAG, "onResourceReady")
                        val height = resource.height
                        val width = resource.width
                        val screenWidth = Tools.getScreenWidth(context)
                        if (width > screenWidth) {
                            val params = view.layoutParams
                            params.height = (height.toFloat() * screenWidth / width).toInt()
                            view.layoutParams = params
                        }
                        //压缩图片
                        async {
                            val bitmap = Tools.bitmapCompress(context, resource)
                            bitmap?.let {
                                uiThread {
                                    view.setImageBitmap(bitmap)
                                }
                            }
                        }
                    }
                }
                Glide.with(view).asBitmap().load(url).into(target)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Tools.elog(TAG, "load img error, url:${url},error:${e}")
            Tools.report(Constant.Event.IMG_LOAD_ERROR, buildMap {
                put("error", e.toString())
            })
        }
    }

}